<?php

/**
 * 先安装workerman包
 * 在根目录创建文件Wm.php，Centos操作：
 * 启动：php wm.php start
 * 停止，新窗口：php wm.php stop
 * 查看进程：netstat -ano | grep 端口号
 */

use Workerman\Worker;
use Workerman\Lib\Timer;
require_once __DIR__ . '/vendor/workerman/workerman/Autoloader.php';
require_once __DIR__ . '/workman/Msg.php';
// 创建一个Worker监听端口
$worker = new Worker('websocket://0.0.0.0:1111');
$worker->name  = 'map';
$worker->count = 1;
//当有客户端发来消息时执行的回调函数
$worker->onMessage = function($connection, $message) {
    $msgs = Msg::jsonToArr($message);
//    $str = $msgs ? $msgs['stamp'] : '?';
    $resMsg = Msg::setAdd($msgs['stamp'],$msgs['uid'],$msgs['msg']);
    $connection->send('请求成功：'.$msgs['t']);
};
//建立定时推送任务
$worker->onWorkerStart = function($worker)  {
    Timer::add(2, function()use($worker){
        foreach($worker->connections as $connection) {
             $connection->send('hello 2S ...');
        }
    });
};
//当有客户端连接断开时
$worker->onClose = function($connection)use($worker) {
    global $worker;
    if(isset($connection->uid)) {
        unset($worker->uidConnections[$connection->uid]);
    }
};
//向所有验证的用户推送数据
function broadcast($message) {
    global $worker;
    foreach($worker->uidConnections as $connection) {
        $connection->send($message);
    }
}
//针对用户推送数据
function sendMessageByUid($uid, $message) {
    global $worker;
    if (isset($worker->uidConnections[$uid])) {
        $connection = $worker->uidConnections[$uid];
        $connection->send($message);
        return true;
    }
    return false;
}
// 运行worker
Worker::runAll();